package com.example.demo.mapper;

import com.example.demo.entity.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class OrderMapper {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;

    private final RowMapper<Order> orderRowMapper = new RowMapper<Order>() {
        @Override
        public Order mapRow(ResultSet rs, int rowNum) throws SQLException {
            Order order = new Order();
            order.setId(rs.getLong("id"));
            order.setOrderNo(rs.getString("order_no"));
            order.setServiceType(rs.getString("service_type"));
            order.setMaterialType(rs.getString("material_type"));
            order.setItemCount(rs.getInt("item_count"));
            order.setSpecialRequirements(rs.getString("special_requirements"));
            order.setItemDescription(rs.getString("item_description"));
            order.setPickupAddress(rs.getString("pickup_address"));
            order.setPickupTime(rs.getString("pickup_time"));
            order.setPickupDate(rs.getString("pickup_date"));
            order.setContactName(rs.getString("contact_name"));
            order.setContactPhone(rs.getString("contact_phone"));
            order.setTotalAmount(rs.getBigDecimal("total_amount"));
            order.setStatus(rs.getString("status"));
            order.setCreateTime(rs.getTimestamp("create_time").toLocalDateTime());
            order.setUpdateTime(rs.getTimestamp("update_time").toLocalDateTime());
            return order;
        }
    };

    public List<Order> findAll() {
        String sql = "SELECT * FROM orders ORDER BY create_time DESC";
        return jdbcTemplate.query(sql, orderRowMapper);
    }

    public Order findById(Long id) {
        String sql = "SELECT * FROM orders WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, orderRowMapper, id);
    }
} 